# ActsAsLoggable
module Acts #:nodoc:
  module Loggable #:nodoc:

    def self.included(base)
      base.extend ClassMethods  
    end

    module ClassMethods
      def acts_as_loggable
        has_many :logs, -> { order('created_at DESC, id DESC') }, :as => :loggable, class_name: '::Log', :dependent => :destroy
        include Acts::Loggable::InstanceMethods
      end
    end

    module InstanceMethods      
      def add_log(actor, owner, action, message=nil, details=nil)
        log = Log.new(user: actor, owner: owner, action: action, message: message)
        log.details = details if details
        logs << log
      end

      def latest_actor
        logs.first.try(:user)
      end

      def latest_action_time
        logs.first.try(:created_at)
      end
    end
  end
end
